package leetcode.d_300_plus;

import java.util.*;

public class P347 {
    class Temp {
        int key;
        int count;
        Temp(int key, int count) {
            this.key = key;
            this.count = count;
        }
    }

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            int count =  map.getOrDefault(num, 0);
            map.put(num, count+1);
        }
        List<Temp> list = new ArrayList<>();
        for (int key : map.keySet()) {
            int count = map.get(key);
            Temp temp = new Temp(key,count);
            list.add(temp);
        }
        Queue<Temp> queue = new PriorityQueue<>((v1, v2) -> v2.count - v1.count);
        for (int i=0; i<list.size(); i++) {
            queue.add(list.get(i));
        }
        int[] res = new int[k];
        int idx = 0;
        while(idx<k){
            res[idx] = queue.poll().key;
            idx++;
        }
        return res;
    }
}
